package com.zjitc.service.imp;

import com.zjitc.common.ServerResponse;
import com.zjitc.dao.CarDao;
import com.zjitc.dao.ProductDao;
import com.zjitc.pojo.Car;
import com.zjitc.pojo.Caritem;
import com.zjitc.service.CarService;
import com.zjitc.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

/**
 * Create By IntelliJ IDEA
 *
 * @author:
 * @create-Time: 2017/11/20  17:07
 */
@Service
public class CarServiceImpl implements CarService {

    @Autowired
    private CarDao cdao;

    @Autowired
    private ProductDao pdao;


    @Override
    public void add2car(String uid, int count, String pid) {
        List<Car> checkcar = cdao.checkcar(uid, pid);
        if(checkcar.size() != 0){
            count = checkcar.get(0).getCount() + count;
            cdao.updatecar(uid,count,pid);
        }else {
            cdao.addnew(uid,count,pid);
        }
    }

    @Override
    public List<Caritem> findAll(String uid) {
        List<Car> checkcar = cdao.checkcar(uid, null);
        List<Caritem> caritems = new ArrayList<Caritem>();
        for(Car car : checkcar){
            Product p = pdao.findbypid(car.getPid());
            caritems.add(new Caritem(p,car.getCount(),p.getShopPrice() * car.getCount()));
        }
        return caritems;
    }

    @Override
    public int deleteAll(String uid) {
        int i = cdao.deleteAll(uid);
        return i;
    }

    @Override
    public ServerResponse<Car> deletesingle(String pid, String uid) {
        try {
            int del = cdao.deletebypid(pid, uid);
            return ServerResponse.createSuccess("1");
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createError("0");
        }
    }
}
